// 聊天室
var url = 'wss://wss.luozejiao.com';
var msgProto = require('MsgProto.js');
var app
var protobuf = require('../../weichatPb/protobuf.js'); //引入protobuf模块
var HallLoginMessage = require('SentBody.js');//加载awesome.proto对应的json
var Message = require('Message.js');
var ReplyBody = require('ReplyBody.js');
function connect(user, func) {
 
  console.log("准备链接")
  wx.connectSocket({
    url: url,
    header: { 'content-type': 'application/json' },
    success: function () {
      console.log('信道连接成功~')
      
    },
    fail: function () {
      console.log('信道连接失败~')
    }
  })
  wx.onSocketOpen(function (res) {
  
  
    let session={
      account: user.id+"",
      channel: "browser",
      appVersion: "1.0.0",
      osVersion: "1.0.0",
      packageName: "com.farsunset.cim",
      deviceId: "1",
      device: "1",
    };
    let ddd = {
      key: "client_bind",
      data: session,
      timestamp: new Date().getTime(),
    };
   
    wx.sendSocketMessage({
      data: loadProtoData(ddd),
      success() {
       

      },
      fail() {
        app.show_("通讯服务断开，正在重连...")
        this.linkSocket()
      }
    });
   // msgProto.MsgProto.sendMsg(session)
 
    //接受服务器消息
    wx.onSocketMessage(func);//func回调可以拿到服务器返回的数据
  });
  wx.onSocketError(function (res) {
    wx.showToast({
      title: '信道连接失败，请检查！',
      icon: "none",
      duration: 2000
    })
  })
}
function loadProtoData(data) {



  console.log("HallLoginMessage-", HallLoginMessage);
  var AwesomeRoot = protobuf.Root.fromJSON(HallLoginMessage);
  console.log("AwesomeRoot-", AwesomeRoot);
  var LoginRequest = AwesomeRoot.lookupType("com.farsunset.cim.sdk.web.model.SentBody");//这就是我们的Message类
  console.log("LoginRequest-", LoginRequest);
  var payload = data;
  var message = LoginRequest.create(payload);
  console.log("message-", message);
  var buffer = LoginRequest.encode(message).finish();
  console.log("buffer", buffer);
 // var arrayBuffer = new ArrayBuffer(4 + buffer.length);
 // var dataView = new DataView(arrayBuffer);
 // dataView.setInt32(0, 10001);
 // for (var i = 0; i < buffer.length; i++) {
   // dataView.setUint8(i + 4, buffer[i]);
 // }
  //console.log("dataView", dataView);
 // console.log("发送的数据---", arrayBuffer);
  return buffer;
}
function stringToUint8Array(str) {
  var arr = [];
  for (var i = 0, j = str.length; i < j; ++i) {
    arr.push(str.charCodeAt(i));
  }

  var tmpUint8Array = new Uint8Array(arr);
  console.log("tmpUint8Array", tmpUint8Array)
  return tmpUint8Array
}


function Uint8ArrayToString(fileData) {
  var dataString = "";
  for (var i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }

  return dataString
}


function objToStrMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}
//发送消息
function send() {
  let session = {
    account: "1",
    channel: "browser",
    appVersion: "1.0.0",
    osVersion: "1.0.0",
    packageName: "com.farsunset.cim",
    deviceId: "1",
    device: "1",
  };
  let ddd = {
    key: "client_bind",

    timestamp: new Date().getTime(),
  };
  loadProtoData(ddd);
}

function receiveMessage(data) {

  console.log("innerOnMessageReceived", data);
  let data2 = new Uint8Array(data);
  let type = data2[0];
  console.log("type", type);
  let body = data2.subarray(1, data2.length);
  console.log("innerOnMessageReceivedbody", body);
  var rrr2 = Uint8ArrayToString(type);
  console.log("rrr2", rrr2);
//接收消息
  if(type===2)
  {
    var AwesomeRoot = protobuf.Root.fromJSON(Message);
    console.log("AwesomeRoot-", AwesomeRoot);
    var LoginRequest = AwesomeRoot.lookupType("com.farsunset.cim.sdk.web.model.Message");//这就是我们的Message类
    console.log("LoginRequest-", LoginRequest);
    let deMessage2 = LoginRequest.decode(body);
    console.log("deMessage2", deMessage2);

    return deMessage2;
  }

  //绑定账号返回
  var AwesomeRoot = protobuf.Root.fromJSON(ReplyBody);
  console.log("AwesomeRoot-", AwesomeRoot);
  var LoginRequest = AwesomeRoot.lookupType("com.farsunset.cim.sdk.web.model.ReplyBody");//这就是我们的Message类
  console.log("LoginRequest-", LoginRequest);
  let deMessage2 = LoginRequest.decode(body);
  console.log("deMessage2", deMessage2);

  return deMessage2;
}

module.exports = {
  connect: connect,
  send: send,
  receiveMessage: receiveMessage,
}